package com.wufeng.controller;

import com.wufeng.dto.R;
import com.wufeng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Autowired
    private UserService userService;


    /**
     * 头像上传
     *
     * @param file
     * @return
     */
    @CrossOrigin
    @PostMapping("/upload")
    public ResponseEntity<R> handleAvatarUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("文件上传");
        R response = new R();

        // 检查文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(response.error("请选择文件"));
        }

        // 检查文件类型，只允许上传图片文件
        if (!file.getContentType().startsWith("image/")) {
            return ResponseEntity.badRequest().body(response.error("只能上传图片文件"));
        }

        try {
            // 获取当前项目的绝对路径
            String projectDir = System.getProperty("user.dir");

            // 指定保存文件的相对路径
            String uploadDir = "src/main/resources/static/imgs/avatar/";

            // 创建目录（如果不存在）
            Path uploadPath = Paths.get(projectDir, uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成UUID作为新的文件名
            String newFileName = UUID.randomUUID().toString() + getFileExtension(file.getOriginalFilename());

            // 保存文件到指定目录
            Path filePath = uploadPath.resolve(newFileName);
            Files.copy(file.getInputStream(), filePath);

//            // 返回文件访问的URL
//            String fileUrl = "/imgs/avatar/" + newFileName;
//            System.out.println(fileUrl);
//            response.put("fileUrl", fileUrl);
            // 返回文件名
            System.out.println(newFileName);
            response.put("fileName", newFileName);

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            return ResponseEntity.status(500).body(response.error("文件上传失败"));
        }
    }

    // 获取文件扩展名的方法
    private String getFileExtension(String originalFilename) {
        int dotIndex = originalFilename.lastIndexOf('.');
        return (dotIndex == -1) ? "" : originalFilename.substring(dotIndex);
    }
}
